﻿using Orchard.ContentManagement.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EcoTourEduca.BingYourMaps.Models;
using Orchard.Data;
using Orchard.ContentManagement;
using EcoTourEduca.BingYourMaps.Services;

namespace EcoTourEduca.BingYourMaps.Handlers
{
    public class BingMapsAreaHandler : ContentHandler
    {
        private readonly IContentManager _contentManager;
        private readonly IBingYourMapsService _service;
        private readonly IRepository<BingMapsAreaRecord> _repository;

        public BingMapsAreaHandler(IRepository<BingMapsAreaRecord> repository
                                ,IBingYourMapsService service
                                ,IContentManager contentManager)
        {
            Filters.Add(StorageFilter.For(repository));
            _repository = repository;
            _contentManager = contentManager;
            _service = service;

            OnLoading<BingMapsAreaPart>(LazyLoadHandler);
            OnRemoved<BingMapsAreaPart>(AreaMappingRemovalHandler);
            //OnInitializing<BingMapsAreaPart>(PropertySetHandlers);
            //OnLoaded<BingMapsAreaPart>(LazyLoadHandlers);
        }

        private void AreaMappingRemovalHandler(RemoveContentContext context, BingMapsAreaPart areaPart)
        {
            if (areaPart != null)
            {
                _service.RemoveMappingsForBingMapsArea(areaPart);
                _repository.Delete(areaPart.Record); // Base Handler doesn't by default remove part records
            }
        }

        private void LazyLoadHandler(LoadContentContext context, BingMapsAreaPart areaPart)
        {
            // Lazy load BingMapsLocations for BingMapsArea
            IEnumerable<BingMapsLocationPart> locations = _service.GetBingMapsLocationPartsForAreaPart(areaPart.Id);
            areaPart.BingMapsLocations = locations != null ? locations : new List<BingMapsLocationPart>();
        }
    }
}